package com.ricky.net;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

import org.apache.log4j.Logger;

import com.ricky.config.ConfigData;
import com.ricky.core.net.MinaServer;
import com.ricky.core.net.abs.Request;
import com.ricky.core.net.abs.NetServer;
import com.ricky.core.net.i.IMessageListener;
import com.ricky.core.net.i.IServerListener;
import com.ricky.core.net.msg.AMF3Context;
import com.ricky.core.net.msg.Context;
import com.ricky.core.net.msg.StringContext;
import com.ricky.handler.Default;
import com.ricky.job.Authorise;
import com.ricky.job.MsgTask;

/***
 *	AgentServer.java</br>
 *	@author pu
 *  @Data 2011-11-1</br>
 *	@version v0.1</br>
 *	@Discription 游戏服务
 ***/
public class GameServer implements IMessageListener<Context<?>>,IServerListener {
	
	protected static Logger log = Logger.getLogger(GameServer.class);

	/**
	 * 连接服务
	 */
	public NetServer minaServer;

	/**
	 * 消息处理器
	 */
	public ExecutorService workQueue;

	/**
	 * 初始化
	 */
	public void init() {

		int nThreads = Runtime.getRuntime().availableProcessors() * 2;
		if (nThreads < 4) {
			nThreads = 4;
		}
		
		workQueue =Executors.newFixedThreadPool(nThreads);//.newSingleThreadExecutor();// GM消息处理一个线程
		
		int port =  ConfigData.serverinfo.getPort();
		minaServer = new MinaServer(port, 5000);
		minaServer.setIserverListener(this);
		minaServer.setIMessageListener(this);
		minaServer.init();
	}

	/**
	 * 启动
	 */
	public void start() {
		minaServer.start();
		log.info("游戏服务器已启动"+ConfigData.serverinfo.getAppName()+ ConfigData.serverinfo.getPort());
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.ricky.core.net.i.IServerListener#onMessageArrived(com.ricky.core
	 * .net.Context)
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public void onMessageArrived(Request request,Context context) {
		if(request.isValidate())//登录
			workQueue.submit(new MsgTask(request,context));
		else
			workQueue.submit(new Authorise(request,context));
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.ricky.core.net.i.IServerListener#onConnectionOpend(com.ricky.core
	 * .net.abs.NetConnection)
	 */
	@Override
	public void onConnectionOpend(Request conn) {

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.ricky.core.net.i.IServerListener#onConnectionClosed(com.ricky.
	 * gmAgent.net.abs.NetConnection)
	 */
	@Override
	public void onConnectionClosed(Request request) {
		
		Context sc=new AMF3Context();
		sc.setHead("onExit");
		workQueue.submit(new Authorise(request,sc));
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.ricky.core.net.i.IServerListener#onConnectionCreated(com.ricky
	 * .gmAgent.net.abs.NetConnection)
	 */
	@Override
	public void onConnectionCreated(Request conn) {

		conn.register(Default.defaultHandName,new Default());

	}

}
